<template>
  <div :ref="chartId" :style="{ width: chartWidth, height: chartHeight }"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    chartId: {
      type: String,
      default: 'BarChart'
    },
    chartWidth: {
      type: String,
      default: '100%'
    },
    chartHeight: {
      type: String,
      default: '100%'
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.drawStackedBarChart();
  },
  methods: {
    drawStackedBarChart() {
      let newData=[];
      let uniquePestNames=[];
      let unit=[];
      if(this.chartId==='id1') {
        const allPestNames = [];
        this.data.forEach(item => {
          const pestNames = Object.keys(item.pests);
          allPestNames.push(...pestNames);
        });
        uniquePestNames = Array.from(new Set(allPestNames));
        newData = this.data.map(item => {
          let pestsData = uniquePestNames.map(name => {
            return item.pests[name] || 0;
          });
          return {
            label: item.label,
            pests: pestsData
          };
        });
      }else{
        newData=[{
          label:Object.keys(this.data[0]),
          pests:Object.values(this.data[0])
        }]
        uniquePestNames=Object.keys(this.data[0])
      if(this.chartId=='id2'){unit= {show: true, position: 'top', formatter: '{c}m³',}}
      else {unit= {show: true, position: 'top', formatter: '{c}度',}}
      }
      this.chart = echarts.init(this.$refs[this.chartId]);
        const option = {
          legend: {
            top: 'top',
            data: newData.map(item => item.label)
          },
          grid:{
            top:'22%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            data: uniquePestNames
          },
          yAxis: {},
          tooltip: {
            trigger: 'axis'
          },
          series:newData.map(item => ({
            type: 'bar',
            name: item.label,
            data: item.pests,
            label: unit
          }))
        };
        this.chart.setOption(option);
    }
  },
  watch: {
    insectSData: 'drawStackedBarChart',
    data:'drawStackedBarChart'
  },
};
</script>

